﻿using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using RESTController.Lib;
using RESTController.Properties;

namespace RESTController
{
    public static class HtmlHelperExtensions
    {
        private static void ClearFlashFromTempData(HtmlHelper htmlHelper)
        {
            htmlHelper.ViewContext.TempData.ClearFlashFromTempData();
        }

        private static string GetFlashCssClass(FlashType flashType)
        {
            switch (flashType)
            {
                case FlashType.Info:
                    return "flashInfo";
                case FlashType.Success:
                    return "flashSuccess";
                case FlashType.Warning:
                    return "flashWarning";
                case FlashType.Error:
                    return "flashError";
                default:
                    return "flash";
            }
        }

        private static string GetFlashMessage(HtmlHelper htmlHelper)
        {
            return htmlHelper.ViewContext.TempData[RESTControllerContants.FLASH_MESSAGE] as string ?? "";
        }

        private static FlashType GetFlashType(HtmlHelper htmlHelper)
        {
            var flashType = htmlHelper.ViewContext.TempData[RESTControllerContants.FLASH_TYPE];
            return (flashType == null) ? FlashType.None : (FlashType)flashType;            
        }

        private static string GetPager()
        {
            var rand = new Random();
            return "pager" + rand.Next(99999999).ToString("D9");
        }

        public static IHtmlString WriteFlash<TModel>(this HtmlHelper<TModel> htmlHelper)
        {
            var flashType = GetFlashType(htmlHelper);
            if (flashType == FlashType.None)
            {
                return new HtmlString("");
            }
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("<div class=\"flashWrapper\"><div class=\"{0}\">", GetFlashCssClass(flashType));
            stringBuilder.Append(htmlHelper.Encode(GetFlashMessage(htmlHelper)));
            stringBuilder.Append("</div></div>");            
            ClearFlashFromTempData(htmlHelper);
            return new HtmlString(stringBuilder.ToString());
        }

        public static IHtmlString WritePager(this HtmlHelper htmlHelper, string containerId, string listUrl, string countUrl)
        {
            //var response = htmlHelper.GetResponse();
            var pager = GetPager();
            var html = Resources.PagerMarkup;
            html = html.Replace("{{containerId}}", containerId);
            html = html.Replace("{{listUrl}}", listUrl);
            html = html.Replace("{{countUrl}}", countUrl);
            html = html.Replace("{{pager}}", pager);
            //response.Write(html);
            return new HtmlString(html);
        }
    }
}
